const app = getApp();

Page({
  data: {
    cartItems: [],
    selectedIds: [],
    totalPrice: 0,
    totalCount: 0,
    loading: true,
    isEditing: false
  },

  onShow() {
    this.loadCartItems();
  },

  async loadCartItems() {
    try {
      const res = await app.request({
        url: '/cart/',
        method: 'GET'
      });
      console.log('购物车数据:', res);
      
      this.setData({
        cartItems: res.data || [],
        loading: false,
        selectedIds: [] // 重置选中状态
      });
      this.calculateTotal();
    } catch (error) {
      console.error('获取购物车列表失败', error);
      this.setData({ 
        loading: false,
        cartItems: [],
        selectedIds: []
      });
      wx.showToast({
        title: '获取购物车失败',
        icon: 'none'
      });
    }
  },

  handleSelect(e) {
    const { id } = e.currentTarget.dataset;
    console.log('选中商品ID:', id);
    const { selectedIds } = this.data;
    const index = selectedIds.indexOf(id);
    
    let newSelectedIds;
    if (index > -1) {
      newSelectedIds = selectedIds.filter(item => item !== id);
    } else {
      newSelectedIds = [...selectedIds, id];
    }

    console.log('更新后的selectedIds:', newSelectedIds);
    this.setData({ 
      selectedIds: newSelectedIds
    });
    this.calculateTotal();
  },

  handleSelectAll() {
    const { cartItems, selectedIds } = this.data;
    if (selectedIds.length === cartItems.length) {
      this.setData({ selectedIds: [] });
    } else {
      this.setData({
        selectedIds: cartItems.map(item => item.id)
      });
    }
    this.calculateTotal();
  },

  calculateTotal() {
    const { cartItems, selectedIds } = this.data;
    console.log('计算总价 - cartItems:', cartItems);
    console.log('计算总价 - selectedIds:', selectedIds);
    
    let totalPrice = 0;
    let totalCount = 0;

    cartItems.forEach(item => {
      if (selectedIds.includes(item.id)) {
        const price = parseFloat(item.product.price);
        totalPrice += price * item.quantity;
        totalCount += item.quantity;
      }
    });

    console.log('计算结果 - totalPrice:', totalPrice, 'totalCount:', totalCount);
    this.setData({
      totalPrice: totalPrice.toFixed(2),
      totalCount
    });
  },

  async handleQuantityChange(e) {
    const { id, type } = e.currentTarget.dataset;
    console.log('修改数量:', id, type);
    const item = this.data.cartItems.find(item => item.id === id);
    if (!item) return;
    
    let { quantity } = item;

    if (type === 'minus' && quantity > 1) {
      quantity--;
    } else if (type === 'plus' && quantity < item.product.stock) {
      quantity++;
    } else {
      return;
    }

    try {
      const res = await app.request({
        url: '/cart/update_quantity/',
        method: 'POST',
        data: { 
          cart_item_id: id,
          quantity 
        }
      });

      console.log('更新数量响应:', res);
      if (res.code === 200) {
        const cartItems = this.data.cartItems.map(item => {
          if (item.id === id) {
            return { ...item, quantity };
          }
          return item;
        });
        this.setData({ cartItems });
        this.calculateTotal();
      } else {
        throw new Error(res.msg || '更新失败');
      }
    } catch (error) {
      console.error('更新购物车数量失败', error);
      wx.showToast({
        title: error.message || '更新数量失败',
        icon: 'none'
      });
    }
  },

  toggleEditMode() {
    this.setData({
      isEditing: !this.data.isEditing,
      selectedIds: []
    });
  },

  async handleDelete() {
    const { selectedIds } = this.data;
    if (selectedIds.length === 0) {
      return;
    }

    wx.showModal({
      title: '提示',
      content: '确定要删除所选商品吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await app.request({
              url: '/cart/clear/',
              method: 'POST',
              data: { ids: selectedIds }
            });

            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });
            this.loadCartItems();
            this.setData({ selectedIds: [] });
          } catch (error) {
            console.error('删除失败', error);
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  handleGoShopping() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  handleCheckout() {
    const { selectedIds } = this.data;
    if (selectedIds.length === 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: `/pages/order/confirm/confirm?cartIds=${selectedIds.join(',')}`
    });
  }
}); 